<template>
	<view class="container">
		<!-- 头部导航 -->
		<view class="header-bag">
			<image src="../../static/icons/icon-Get-into@3.png" class="back" @click="goBack"></image>
			<view class="header-center">
				<text>支付订单</text>
			</view>
		</view>

		<!-- 订单内容 -->
		<view class="wrapper">
			<!-- 商品信息 -->
			<view class="product-info" v-if="orderInfo.title">
				<view class="product-image">
					<image :src="baseUrl+orderInfo.main_img" mode="aspectFill"></image>
				</view>
				<view class="product-details">
					<text class="product-title">{{ orderInfo.title }}</text>
					<text class="product-intro">{{ orderInfo.intro }}</text>
				</view>
			</view>

			<!-- 购买数量 -->
			<view class="quantity-section">
				<text class="label">购买数量</text>
				<view class="quantity-controls">
					<view class="btn-decrease" @click="decreaseQuantity">
						<image src="../../static/img/o2o/jian.png"></image>
					</view>
					<text class="quantity">{{ quantity }}</text>
					<view class="btn-increase" @click="increaseQuantity">
						<image src="../../static/img/o2o/jia.png"></image>
					</view>
				</view>
			</view>

			<!-- 价格信息 -->
			<view class="price-item">
				<text class="label">单价</text>
				<text class="price">￥{{ orderInfo.price }}</text>
			</view>

			<view class="price-item">
				<text class="label">总价</text>
				<text class="price">￥{{ totalPrice }}</text>
			</view>

			<view class="price-item margin-top">
				<text class="label">本次消费分润</text>
				<text class="price">￥{{ totalRebate }}</text>
			</view>

			<view class="price-item margin-top">
				<text class="label">实付金额</text>
				<text class="price highlight">￥{{ totalPrice }}</text>
			</view>

			<view class="price-item margin-top">
				<text class="label">手机号（会员）</text>
				<text class="price">{{ orderInfo.phone || '' }}</text>
			</view>

			<!-- 立即支付按钮 -->
			<view class="pay-button" @click="showPaymentModal">
				<text>立即支付 ¥{{ totalPrice }}</text>
			</view>
		</view>

		<!-- 支付方式弹窗 -->
		<view class="payment-modal" v-if="showPayModal" @click="hidePaymentModal">
			<view class="payment-content" @click.stop>
				<view class="close-btn" @click="hidePaymentModal"></view>
				<view class="payment-header">确认付款</view>
				<view class="payment-amount">￥{{ totalPrice }}</view>
				
				<!-- 余额支付 -->
				<view class="payment-method" @click="selectPaymentMethod('balance')">
					<text>账户余额</text>
					<text class="balance">￥{{ userBalance }}</text>
				</view>
				
				<!-- 微信支付 -->
				<view class="payment-method" @click="selectPaymentMethod('wechat')">
					<text>微信支付</text>
					<image src="../../static/icons/icon-gengduo@2x.png" class="arrow"></image>
				</view>
				
				<!-- 银联支付 -->
				<view class="payment-method" @click="selectPaymentMethod('union')">
					<text>银联支付</text>
					<image src="../../static/icons/icon-gengduo@2x.png" class="arrow"></image>
				</view>
			</view>
		</view>

		<!-- 支付密码弹窗 -->
		<view class="password-modal" v-if="showPasswordModal">
			<view class="password-header">
				<image src="../../static/icons/icon-Get-into@3.png" class="back" @click="hidePasswordModal"></image>
				<text class="title">{{ passwordTitle }}</text>
			</view>
			<view class="password-content">
				<text class="password-tip">请输入支付密码</text>
				<input 
					type="password" 
					maxlength="6" 
					v-model="payPassword" 
					@input="onPasswordInput"
					class="password-input"
					:focus="showPasswordModal"
				/>
			</view>
		</view>

		<!-- 银联支付表单 -->
		<form ref="unionPayForm" style="display: none;"></form>
	</view>
</template>

<script>
import { o2oApi, paymentApi } from '@/api/index.js'
import { getToken, getCurrentUser } from '@/api/auth.js'
import {
		inject
	} from 'vue'

export default {
	data() {
		return {
			baseUrl: inject('$baseUrl'),
			groupId: '',
			storeId: '',
			orderInfo: {},
			quantity: 1,
			orderNum: '',
			userBalance: '0.00',
			showPayModal: false,
			showPasswordModal: false,
			payPassword: '',
			passwordTitle: '检验支付密码',
			isSettingPassword: false,
			firstPassword: '',
			secondPassword: ''
		}
	},
	
	computed: {
		totalPrice() {
			return (parseFloat(this.orderInfo.price || 0) * this.quantity).toFixed(2)
		},
		
		totalRebate() {
			return (parseFloat(this.orderInfo.rebate_price || 0) * this.quantity).toFixed(2)
		}
	},
	
	onLoad(options) {
		this.groupId = options.group_id || ''
		this.storeId = options.store_id || ''
		this.loadOrderInfo()
		this.loadUserBalance()
	},
	
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		
		
		// 加载订单信息
		async loadOrderInfo() {
			try {
				const res = await o2oApi.getPayOrder({
					group_id: this.groupId,
					merch_id: this.storeId
				})
				
				if (res.r === 0) {
					this.orderInfo = res.data
				} else {
					uni.showToast({
						title: res.msg || '获取订单信息失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载订单信息失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 加载用户余额
		async loadUserBalance() {
			try {
				const res = await paymentApi.getUserBalance()
				if (res.r === 0) {
					this.userBalance = res.data.money || '0.00'
				}
			} catch (error) {
				console.error('获取用户余额失败:', error)
			}
		},
		
		// 增加数量
		increaseQuantity() {
			const maximum = parseInt(this.orderInfo.maximum || 999)
			if (this.quantity >= maximum) {
				uni.showToast({
					title: `该商品最多购买${maximum}份！`,
					icon: 'none'
				})
				return
			}
			this.quantity++
		},
		
		// 减少数量
		decreaseQuantity() {
			if (this.quantity <= 1) {
				uni.showToast({
					title: '该商品最少买1份！',
					icon: 'none'
				})
				return
			}
			this.quantity--
		},
		
		// 显示支付弹窗
		async showPaymentModal() {
			try {
				// 先提交订单
				const res = await o2oApi.buyGroup({
					group_id: this.groupId,
					merch_id: this.storeId,
					num: this.quantity
				})
				
				if (res.r === 0) {
					this.orderNum = res.data.order_num
					this.showPayModal = true
					uni.showToast({
						title: res.msg || '订单创建成功',
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: res.msg || '订单创建失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('创建订单失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 隐藏支付弹窗
		hidePaymentModal() {
			this.showPayModal = false
		},
		
		// 选择支付方式
		selectPaymentMethod(method) {
			this.hidePaymentModal()
			
			switch (method) {
				case 'balance':
					this.handleBalancePay()
					break
				case 'wechat':
					this.handleWechatPay()
					break
				case 'union':
					this.handleUnionPay()
					break
			}
		},
		
		// 余额支付
		async handleBalancePay() {
			this.showPasswordModal = true
			await this.checkPayPassword()
		},
		
		// 微信支付
		async handleWechatPay() {
			try {
				const openid = uni.getStorageSync('openid') || ''
				const res = await paymentApi.wechatPay({
					order_num: this.orderNum,
					source: 5,
					type: 6,
					is_father_order: 1,
					openid: openid
				})
				
				if (res.r === 0) {
					this.processWechatPay(res.data)
				} else {
					uni.showToast({
						title: res.msg || '微信支付失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('微信支付失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 处理微信支付
		processWechatPay(payData) {
			// 在小程序中调用微信支付
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: payData.timeStamp.toString(),
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign,
				success: (res) => {
					this.handlePaymentSuccess('微信支付')
				},
				fail: (err) => {
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 银联支付
		async handleUnionPay() {
			try {
				const res = await paymentApi.unionPay({
					order_num: this.orderNum,
					source: 2,
					type: 6,
					is_father_order: 2
				})
				
				if (res.r === 0) {
					// 银联支付需要跳转到银联页面
					// 这里需要根据实际情况处理
					console.log('银联支付数据:', res.data)
				} else {
					uni.showToast({
						title: res.msg || '银联支付失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('银联支付失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 检查支付密码
		async checkPayPassword() {
			try {
				const res = await paymentApi.checkPayPassword()
				if (res.r === 0) {
					this.isSettingPassword = res.data.is_set === 0
					this.passwordTitle = this.isSettingPassword ? '设置支付密码' : '请输入支付密码'
				}
			} catch (error) {
				console.error('检查支付密码失败:', error)
			}
		},
		
		// 密码输入处理
		async onPasswordInput() {
			if (this.payPassword.length < 6) return
			
			// 验证是否为6位数字
			if (!/^\d{6}$/.test(this.payPassword)) {
				uni.showToast({
					title: '支付密码由六位数字组成',
					icon: 'none'
				})
				this.payPassword = ''
				return
			}
			
			if (this.isSettingPassword) {
				await this.handleSetPassword()
			} else {
				await this.handleVerifyPassword()
			}
		},
		
		// 设置支付密码
		async handleSetPassword() {
			if (!this.firstPassword) {
				this.firstPassword = this.payPassword
				this.payPassword = ''
				this.passwordTitle = '请再次输入支付密码'
			} else {
				this.secondPassword = this.payPassword
				
				if (this.firstPassword !== this.secondPassword) {
					uni.showToast({
						title: '两次密码输入不一致',
						icon: 'none'
					})
					this.secondPassword = ''
					this.payPassword = ''
					return
				}
				
				try {
					const res = await paymentApi.setPayPassword({
						pay_pwd: this.md5(this.firstPassword),
						pay_confirm_pwd: this.md5(this.secondPassword)
					})
					
					if (res.r === 0) {
						uni.showToast({
							title: '支付密码设置成功',
							icon: 'success'
						})
						this.isSettingPassword = false
						this.passwordTitle = '请输入支付密码'
						this.payPassword = ''
						this.firstPassword = ''
						this.secondPassword = ''
					} else {
						uni.showToast({
							title: res.msg || '设置失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('设置支付密码失败:', error)
				}
			}
		},
		
		// 验证支付密码
		async handleVerifyPassword() {
			try {
				const res = await paymentApi.verifyPayPassword({
					pay_pwd: this.md5(this.payPassword)
				})
				
				if (res.r === 0) {
					// 密码验证成功，执行余额支付
					await this.processBalancePay()
				} else {
					uni.showToast({
						title: res.msg || '密码错误',
						icon: 'none'
					})
					this.payPassword = ''
				}
			} catch (error) {
				console.error('验证支付密码失败:', error)
				this.payPassword = ''
			}
		},
		
		// 执行余额支付
		async processBalancePay() {
			try {
				const res = await paymentApi.balancePay({
					order_num: this.orderNum,
					type: 6,
					is_father_order: 1,
					num: this.quantity
				})
				
				if (res.r === 0) {
					this.hidePasswordModal()
					this.handlePaymentSuccess('余额支付')
				} else {
					uni.showToast({
						title: res.msg || '支付失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('余额支付失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 隐藏密码弹窗
		hidePasswordModal() {
			this.showPasswordModal = false
			this.payPassword = ''
			this.firstPassword = ''
			this.secondPassword = ''
		},
		
		// 支付成功处理
		handlePaymentSuccess(payType) {
			uni.showToast({
				title: '支付成功',
				icon: 'success'
			})
			
			setTimeout(() => {
				uni.redirectTo({
					url: `/pages/o2o/order-pay-success?type=${payType}&totalMoney=${this.totalPrice}&order_num=${this.orderNum}`
				})
			}, 1000)
		},
		
		// MD5加密（需要引入MD5库或使用简单实现）
		md5(str) {
			// 这里需要实现MD5加密，可以使用crypto-js库
			// 临时返回原字符串，实际使用时需要真正的MD5加密
			return str
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	background: #eeeeee;
	min-height: 100vh;
}

.header-bag {
	background: #ff1e00;
	height: 88rpx;
	display: flex;
	align-items: center;
	position: relative;
	
	.back {
		width: 40rpx;
		height: 40rpx;
		margin-left: 30rpx;
	}
	
	.header-center {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		
		text {
			color: white;
			font-size: 36rpx;
		}
	}
}

.wrapper {
	padding: 0 30rpx;
}

.product-info {
	background: white;
	margin-top: 20rpx;
	padding: 30rpx;
	display: flex;
	
	.product-image {
		width: 120rpx;
		height: 120rpx;
		margin-right: 20rpx;
		
		image {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}
	}
	
	.product-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		
		.product-title {
			font-size: 32rpx;
			font-weight: 700;
			color: #333;
			margin-bottom: 10rpx;
		}
		
		.product-intro {
			font-size: 26rpx;
			color: #6e6e6e;
		}
	}
}

.quantity-section {
	background: white;
	height: 90rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	border-top: 1px solid #ddd;
	
	.label {
		font-size: 30rpx;
		color: #212121;
	}
	
	.quantity-controls {
		display: flex;
		align-items: center;
		
		.btn-decrease,
		.btn-increase {
			width: 50rpx;
			height: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			image {
				width: 50rpx;
				height: 50rpx;
			}
		}
		
		.quantity {
			margin: 0 25rpx;
			font-size: 30rpx;
		}
	}
}

.price-item {
	background: white;
	height: 90rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	
	&.margin-top {
		margin-top: 20rpx;
	}
	
	.label {
		font-size: 30rpx;
		color: #212121;
	}
	
	.price {
		font-size: 30rpx;
		color: #444444;
		
		&.highlight {
			color: #ff1e00;
		}
	}
}

.pay-button {
	width: 690rpx;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	background: #ff1e00;
	border-radius: 10rpx;
	margin: 100rpx auto 0;
	
	text {
		color: white;
		font-size: 36rpx;
	}
}

.payment-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
	
	.payment-content {
		background: white;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		padding: 40rpx 30rpx;
		position: relative;
		
		.close-btn {
			position: absolute;
			top: 20rpx;
			right: 30rpx;
			width: 40rpx;
			height: 40rpx;
			background: #ccc;
			border-radius: 50%;
		}
		
		.payment-header {
			font-size: 32rpx;
			text-align: center;
			margin-bottom: 30rpx;
		}
		
		.payment-amount {
			font-size: 48rpx;
			text-align: center;
			color: #ff1e00;
			margin-bottom: 40rpx;
		}
		
		.payment-method {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
			border-bottom: 1px solid #eee;
			
			text {
				font-size: 34rpx;
			}
			
			.balance {
				color: #666;
			}
			
			.arrow {
				width: 24rpx;
				height: 24rpx;
			}
		}
	}
}

.password-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: white;
	z-index: 1001;
	
	.password-header {
		background: #ff1e00;
		height: 88rpx;
		display: flex;
		align-items: center;
		position: relative;
		
		.back {
			width: 40rpx;
			height: 40rpx;
			margin-left: 30rpx;
		}
		
		.title {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			color: white;
			font-size: 36rpx;
		}
	}
	
	.password-content {
		padding: 60rpx 30rpx;
		
		.password-tip {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 40rpx;
		}
		
		.password-input {
			width: 100%;
			height: 80rpx;
			border: 1px solid #ddd;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 32rpx;
		}
	}
}
</style>